<template>
  <XtxDialog
    :title="`${form.id ? '修改' : '添加'}收货地址`"
    v-model="dialogVisible"
  >
    <Form
      class="address-edit"
      :validation-schema="veeValidateSchema"
      v-slot="{ errors }"
      ref="formCom"
    >
      <div class="xtx-form">
        <div class="xtx-form-item">
          <div class="label">收货人：</div>
          <div class="field">
            <Field
              name="receiver"
              v-model="form.receiver"
              class="input"
              placeholder="请输入收货人"
            />
          </div>
          <div class="error">{{ errors.receiver }}</div>
        </div>
        <div class="xtx-form-item">
          <div class="label">手机号：</div>
          <div class="field">
            <Field
              name="mobile"
              v-model="form.contact"
              class="input"
              placeholder="请输入手机号"
            />
          </div>
          <div class="error">{{ errors.mobile }}</div>
        </div>
        <div class="xtx-form-item">
          <div class="label">地区：</div>
          <div class="field">
            <Field
              :fullLocation="form.fullLocation"
              @change="changeCty"
              as='XtxCity'
              name='fullLocation'
              placeholder="请选择所在地区"
            />
          </div>
          <div class="error">{{ errors.fullLocation }}</div>
        </div>
        <div class="xtx-form-item">
          <div class="label">详细地址：</div>
          <div class="field">
            <Field
              name="address"
              v-model="form.address"
              class="input"
              placeholder="请输入详细地址"
            />
          </div>
          <div class="error">{{ errors.address }}</div>
        </div>
        <div class="xtx-form-item">
          <div class="label">邮政编码：</div>
          <div class="field">
            <Field
              name="postalCode"
              v-model="form.postalCode"
              class="input"
              placeholder="请输入邮政编码"
            />
          </div>
          <div class="error">{{ errors.postalCode }}</div>
        </div>
        <div class="xtx-form-item">
          <div class="label">地址标签：</div>
          <div class="field">
            <input
              v-model="form.addressTags"
              class="input"
              placeholder="请输入地址标签，逗号分隔"
            />
          </div>
        </div>
      </div>
    </Form>
    <template #footer>
      <XtxButton
        type="gray"
        style="margin-right: 20px"
        @click="dialogVisible = false"
        >取消</XtxButton
      >
      <XtxButton type="primary" @click="sumbit">确认</XtxButton>
    </template>
  </XtxDialog>
</template>

<script>
import { inject, reactive, ref } from 'vue'
import { addAddress, editAddress } from '@/api/order'
import Message from '@/components/library/Message'
import { Form, Field } from 'vee-validate'
import veeValidateSchema from '@/utils/vee-validate-schema'
export default {
  name: 'AddressEdit',
  components: { Form, Field },
  setup (props, { emit }) {
    const dialogVisible = ref(false)

    // 打开函数
    const open = (showAddress) => {
      dialogVisible.value = true
      // 打开窗口的时候有两个情况：
      // 情况1：修改，如有有地址，就是修改
      if (showAddress) {
        for (const key in form) {
          form[key] = showAddress[key]
        }
      } else {
        // 情况2：添加 - 空表单
        // 清空表单
        formCom.value.resetForm()
        for (const key in form) {
          form[key] = ''
        }
        // 🔔注意：isDefault 的值不是字符串类型，是否为默认地址，0为是，1为否
        form.isDefault = 0
      }
    }

    const form = reactive({
      receiver: '', // 收货人姓名
      contact: '', // 联系方式
      address: '', // 详细地址
      postalCode: '', // 邮政编码
      addressTags: '', // 地址标签,以英文逗号分割
      provinceCode: '', // 所在省份编码
      cityCode: '', // 所在城市编码
      countyCode: '', // 所在区/县编码
      isDefault: 0, // 是否为默认，0为是，1为否
      // 考虑到这个表单对象还要实现修改，所以新增两个修改时所需的字段
      id: '', // 需要修改的地址id
      fullLocation: '' // 完整地址，用于城市组件展示的
    })

    const changeCty = (address) => {
      form.provinceCode = address.provinceCode
      form.cityCode = address.cityCode
      form.countyCode = address.countyCode
      form.fullLocation = address.fullLocation
    }

    const getAddressList = inject('getAddressList')

    const formCom = ref(null)
    // 提交表单
    const sumbit = async () => {
      // 💥我们这里省略了表单校验的代码...
      // 发送请求给服务器，添加新的收货地址
      const valid = await formCom.value.validate()
      // console.log(valid)
      if (valid) {
        // 也要考虑两种情况：
      // 情况1：有 id 是修改
        if (form.id) {
          await editAddress(form)
          // 父组件可以通过 on-success 获取到修改后的表单数据
          emit('on-success', form)
        } else {
        // 情况2：没有id是添加
        // 发送请求给服务器，添加新的收货地址
          await addAddress(form)
        }

        // 成功提示
        Message({
          type: 'success',
          message: `${form.id ? '修改' : '添加'}收货地址成功`
        })
        // 关闭窗口
        dialogVisible.value = false

        // 获取最新的地址列表
        getAddressList()
      } else {
        Message({ type: 'warn', message: '表单验证失败' })
      }
    }
    return { dialogVisible, open, form, changeCty, sumbit, veeValidateSchema, formCom }
  }
}
</script>

<style scoped lang="less">
.xtx-dialog {
  :deep(.wrapper) {
    width: 780px;
    .body {
      font-size: 14px;
    }
  }
}
.xtx-form {
  padding: 0;
  input {
    outline: none;
    &::placeholder {
      color: #ccc;
    }
  }
}
.xtx-city {
  width: 320px;
  :deep(.select) {
    height: 50px;
    line-height: 48px;
    display: flex;
    padding: 0 10px;
    justify-content: space-between;
    .placeholder {
      color: #ccc;
    }
    i {
      color: #ccc;
      font-size: 18px;
    }
    .value {
      font-size: 14px;
    }
  }
  :deep(.option) {
    top: 49px;
  }
}
</style>
